package com.whd.controller;

import com.github.pagehelper.PageInfo;
import com.whd.domain.ResultVo;
import com.whd.entity.Dept;
import com.whd.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author whd
 * @date 2023/07/01 11:03:58
 */
@RestController
@RequestMapping("dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping("{pageNum}/{pageSize}")
    public ResultVo findALl(@PathVariable Integer pageNum, @PathVariable Integer pageSize, HttpSession session) {
        session.setAttribute("pageNum",pageNum);
        session.setAttribute("pageSize", pageSize);

        PageInfo<Dept> pageInfo = deptService.fndAll(pageNum, pageSize);
        List<Dept> deptList = deptService.findAll();
        Map<String, Object> map = new HashMap<>();
        map.put("deptList", deptList);
        map.put("pageInfo", pageInfo);
        return ResultVo.success(map);
    }

    @PostMapping
    public ResultVo save(@RequestBody Dept dept) {
        int rows = deptService.save(dept);
        return rows > 0 ? ResultVo.success("添加成功") : ResultVo.fail("添加失败");
    }
    @DeleteMapping("{deptId}")
    public ResultVo delete(@PathVariable Integer deptId) {
        int rows = deptService.delete(deptId);
        if (rows == -2) {
            return ResultVo.fail("该部门存在员工，不可删除");
        }
        if (rows == -1) {
            return ResultVo.fail("该部门存在子部门，不可删除");
        }
        return rows == 1 ? ResultVo.success("删除成功") : ResultVo.fail("删除失败");
    }

    @PutMapping
    public ResultVo update(@RequestBody Dept dept) {
        int rows = deptService.update(dept);
        return rows > 0 ? ResultVo.success("修改成功") : ResultVo.fail("修改失败");
    }

    @PostMapping("other")
    public ResultVo findByOther(@RequestBody Map<String ,Object> map){
        PageInfo<Dept> pageInfo = deptService.findByOther(map);
        return ResultVo.success(pageInfo);
    }
}
